<?php
namespace app\common\repositories\info;
use app\common\repositories\BaseRepository;
use app\common\dao\info\MapTaskDao as dao;
use app\common\repositories\user\UserRepository;
use basic\services\LocationSearchService;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * @mixin dao
 */
class MapTaskRepository extends BaseRepository
{
    public function __construct(dao $dao)
    {
        $this->dao = $dao;
    }


    public function getApiLst($where,$page,$limit)
    {
        $count = $this->dao->search($where)->count();
        $list = $this->dao->search($where)->order('task_id desc')->page($page,$limit)->select();

        return compact('list','count');
    }


    public function getList($where,$page,$limit)
    {

    }




    public function runTask($search){
        $user = request()->userInfo();
        if($user->integral < $search['count']){
            throw new ValidateException('剩余获客次数不足！');
        }

        try {
            $record = LocationSearchService::create($search['map_type'])->searchLocation($search);
        }catch (\Exception $exception){
            throw  new ValidateException('任务失败！'.$exception->getMessage());
        }

        if(!count($record)){
            throw new ValidateException('未获取到数据!');
        }


        return Db::transaction(function ()use($record,$user,$search){

            $data = [
                'uid'=>$user->uid,
                'keyword'=>$search['keywords'],
                'map_type'=>$search['map_type'],
                'search_type'=>$search['search_type'],
                'count'=>$search['count'],
                'get_count'=>count($record),
                'status'=>2,
                'filter'=>$search['filter'],
                'city'=>$search['city'],
                'lat'=>$search['lat'],
                'lng'=>$search['lng'],
                'range'=>$search['range'],
            ];

            $task = $this->dao->create($data);

            foreach ($record as &$item){
                $item['uid'] = $user->uid;
                $item['task_id'] = $task->task_id;
                $item['map_type'] = $search['map_type'];
                $item['uid'] = $user->uid;
                $item['keyword'] = $data['keyword'];
            }

            /**@var $recordMake MapTaskRecordRepository**/
            $recordMake = app()->make(MapTaskRecordRepository::class);
            $recordMake->insertAll($record);


            // 扣除
            app()->make(UserIntegralRepository::class)->subIntegral($user->uid,$data['get_count'],'获客消耗');
           // app()->make(UserRepository::class)->incrNumberField($user->uid,'integral',$data['get_count']*-1);

            return $record;
        });
    }
}